package wbbs.web.admin;

import cn.webwheel.Action;
import cn.webwheel.results.ErrorResult;
import cn.webwheel.results.TemplateResult;
import wbbs.domain.User;
import wbbs.service.Utils;

import java.sql.SQLException;

public class user extends BaseAction {

    public User user;

    public String pwd;

    public boolean create;

    @Action
    public Object html(String id) throws SQLException {

        ensureLoginPage();

        if (id == null) {
            user = new User();
        } else {
            user = userService.findUser(id);
            if (user == null) {
                return new ErrorResult(404);
            }
        }
        return new TemplateResult(this);
    }

    @Action
    public Object update() throws SQLException {

        ensureLoginAction();

        range(id(notNull(user.id)), 2, 12);
        user.name = range(notNull(trim(user.name)), 1, 32);
        if (!create && pwd.isEmpty()) {
            User u = userService.findUser(user.id);
            notNull(u, "用户不存在");
            user.pwd = u.pwd;
        } else {
            range(notNull(pwd), 6, 15);
            user.pwd = Utils.md5(pwd);
        }
        user.head = notNull(trim(user.head));
        if (create) {
            userService.insertUser(user);
        } else {
            userService.updateUser(user);
        }
        return ok().set("id", user.id);
    }
}
